package com.mxpio.erp.technology.controller;


import com.mxpio.erp.common.enums.OrderStatusEnums;
import com.mxpio.erp.common.technology.entity.BomInfoAudit;
import com.mxpio.erp.common.technology.entity.BomInfoLineTmp;
import com.mxpio.erp.common.technology.entity.BomInfoTmp;
import com.mxpio.erp.common.technology.service.BomInfoAuditService;
import com.mxpio.erp.common.technology.service.BomInfoLineTmpService;
import com.mxpio.erp.common.technology.service.BomInfoTmpService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.List;

@Tag(name = "BomInfoTmpController", description = "Bom草稿接口")
@RestController
@RequestMapping("/erp/tech/bom/tmp")
public class BomInfoTmpController {

    @Autowired
    private BomInfoTmpService bomInfoTmpService;

    @Autowired
    private BomInfoLineTmpService bomInfoLineTmpService;

    @Autowired
    private BomInfoAuditService bomInfoAuditService;

    @GetMapping("listByItem/{itemCode}")
    @Operation(summary = "Bom列表", description = "获取Bom列表（无分页）", method = "GET")
    public Result<BomInfoTmp> listByItem(@Parameter(description="父物料编号") @PathVariable(name = "itemCode", required = true) String itemCode){
        BomInfoTmp bomInfo = bomInfoTmpService.listBomTmp(itemCode);
        return Result.OK(bomInfo);
    }

    @GetMapping("list")
    @Operation(summary = "Bom列表", description = "获取Bom列表（无分页）", method = "GET")
    public Result<List<BomInfoTmp>> list(Criteria criteria) throws UnsupportedEncodingException {
        List<BomInfoTmp> bomInfos = bomInfoTmpService.list(BomInfoTmp.class,criteria);
        return Result.OK(bomInfos);
    }
    @GetMapping("page")
    @Operation(summary = "Bom分页，以物料为基础展示", description = "获取Bom列表（分页）", method = "GET")
    public Result<Page<BomInfoTmp>> page(Criteria criteria, Integer pageNo, Integer pageSize) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        return Result.OK(bomInfoTmpService.page(page,criteria));
    }


    @GetMapping("list/{bomId}")
    @Operation(summary = "根据BomId获取Bom", description = "根据bomId获取Bom", method = "GET")
    public Result<BomInfoTmp> getById(@PathVariable(name = "bomId", required = true) String bomId) {
        BomInfoTmp bomInfo = bomInfoTmpService.getById(BomInfoTmp.class, bomId);
        return Result.OK(bomInfo);
    }

    @RequestMapping("save")
    @Operation(summary = "保存Bom", description = "保存Bom")
    public Result<BomInfoTmp> save(@RequestBody BomInfoTmp bomInfo) {

        if(StringUtils.isNotBlank(bomInfo.getBomId())){
            BomInfoAudit audit = bomInfoAuditService.getById(BomInfoAudit.class,bomInfo.getBomId());
            if(audit!=null){
                return Result.error("已提交审核");
            }
        }

        if(!bomInfoTmpService.validBeginTime(bomInfo)){
            return Result.error("生效日期必须大于当前最新版本的生效日期");
        }

        bomInfoTmpService.save(bomInfo,new SmartCrudPolicyAdapter(){
            @Override
            public boolean beforeInsert(CrudContext context) {
                Object o = context.getEntity();
                if(o instanceof BomInfoLineTmp){
                    ((BomInfoLineTmp) o).setBomId(bomInfo.getBomId());
                }
                return true;
            }
        });
        return Result.OK(bomInfo);
    }

    @RequestMapping("saveAndSubmit")
    @Operation(summary = "保存并提交Bom", description = "保存并提交Bom")
    public Result<BomInfoTmp> saveAndSubmit(@RequestBody BomInfoTmp bomInfo) {

        if(!bomInfoTmpService.validBeginTime(bomInfo)){
            return Result.error("生效日期必须大于当前最新版本的生效日期");
        }

        if(StringUtils.isNotBlank(bomInfo.getBomId())){
            BomInfoTmp bomInfoTmp = bomInfoTmpService.getById(BomInfoTmp.class,bomInfo.getBomId());
            if(bomInfoTmp!=null && !OrderStatusEnums.BomStatus.CREATE.getStatusCode().equals(bomInfoTmp.getUseType())
                    && !OrderStatusEnums.BomStatus.AUDITING.getStatusCode().equals(bomInfoTmp.getUseType())){
                return Result.error("已提交审核");
            }

            BomInfoAudit audit = bomInfoAuditService.getById(BomInfoAudit.class,bomInfo.getBomId());
            if(audit!=null){
                return Result.error("已提交审核");
            }

        }
        bomInfoTmpService.save(bomInfo,new SmartCrudPolicyAdapter(){
            @Override
            public boolean beforeInsert(CrudContext context) {
                Object o = context.getEntity();
                if(o instanceof BomInfoLineTmp){
                    ((BomInfoLineTmp) o).setBomId(bomInfo.getBomId());
                }
                return true;
            }
        });
        if(bomInfoTmpService.audit(bomInfo.getBomId())){
            return Result.OK(bomInfo);
        }
        return Result.error("提交出错");
    }

    @DeleteMapping("remove/{bomIds}")
    @Operation(summary = "根据bomId删除Bom", description = "删除Bom", method = "DELETE")
    @Transactional(readOnly = false)
    public Result<BomInfoTmp> remove(@Parameter(description="bomId，多个单号用英文逗号分隔") @PathVariable(name = "bomIds", required = true) String bomIds) {
        String[] bomId = bomIds.split(",");
        for(String key : bomId){
            Criteria c = Criteria.create().addCriterion("bomId", Operator.EQ, key);
            bomInfoLineTmpService.removeBatch(BomInfoLineTmp.class, c);
            bomInfoTmpService.delete(BomInfoTmp.class, key);
        }
        return Result.OK();
    }

    @PutMapping("submit/{bomId}")
    @Operation(summary = "提交Bom", description = "提交Bom", method = "PUT")
    public Result<BomInfoTmp> submit(@Parameter(description="bomId") @PathVariable(name = "bomId", required = true) String bomId) {
        BomInfoTmp bomInfo = bomInfoTmpService.getById(BomInfoTmp.class,bomId);
        if(bomInfo.getUseType().equals(OrderStatusEnums.BomStatus.CREATE.getStatusCode())){
            return bomInfoTmpService.updateBomStatus(bomInfo, OrderStatusEnums.BomStatus.AUDITING);
        }else {
            return Result.error("非新增状态不可提交");
        }
    }

    @PutMapping("audit/{bomId}")
    @Operation(summary = "审核Bom", description = "审核Bom", method = "PUT")
    public Result<BomInfoTmp> audit(@Parameter(description="bomId") @PathVariable(name = "bomId", required = true) String bomId) {
        BomInfoTmp bomInfo = bomInfoTmpService.getById(BomInfoTmp.class,bomId);
        if(bomInfo.getUseType().equals(OrderStatusEnums.BomStatus.CREATE.getStatusCode())){
            return bomInfoTmpService.updateBomStatus(bomInfo, OrderStatusEnums.BomStatus.USING);
        }else {
            return Result.error("非审核中状态不可审核");
        }
    }

    @PutMapping("abandon/{bomId}")
    @Operation(summary = "弃审Bom", description = "弃审Bom", method = "PUT")
    public Result<BomInfoTmp> abandon(@Parameter(description="bomId") @PathVariable(name = "bomId", required = true) String bomId) {
        BomInfoTmp bomInfo = bomInfoTmpService.getById(BomInfoTmp.class,bomId);
        if(bomInfo.getUseType().equals(OrderStatusEnums.BomStatus.AUDITING.getStatusCode())){
            return bomInfoTmpService.updateBomStatus(bomInfo, OrderStatusEnums.BomStatus.CREATE);
        }else{
            return Result.error("非审核中状态不可审核");
        }
    }

    @PutMapping("expired/{bomId}")
    @Operation(summary = "失效Bom", description = "失效Bom", method = "PUT")
    public Result<BomInfoTmp> expired(@Parameter(description="bomId") @PathVariable(name = "bomId", required = true) String bomId) {
        BomInfoTmp bomInfo = bomInfoTmpService.getById(BomInfoTmp.class,bomId);
        return bomInfoTmpService.updateBomStatus(bomInfo, OrderStatusEnums.BomStatus.EXPIRED);
    }
    @PutMapping("voided/{bomId}")
    @Operation(summary = "作废Bom", description = "作废Bom", method = "PUT")
    public Result<BomInfoTmp> voided(@Parameter(description="bomId") @PathVariable(name = "bomId", required = true) String bomId) {
        BomInfoTmp bomInfo = bomInfoTmpService.getById(BomInfoTmp.class,bomId);
        return bomInfoTmpService.updateBomStatus(bomInfo, OrderStatusEnums.BomStatus.CREATE);
    }

    @PutMapping("toAudit/{bomId}")
    @Operation(summary = "提交Bom至审批功能", description = "提交Bom至审批功能", method = "PUT")
    public Result<BomInfoTmp> toAudit(@Parameter(description="bomId") @PathVariable(name = "bomId", required = true) String bomId) {
        BomInfoTmp bomInfoTmp = bomInfoTmpService.getById(BomInfoTmp.class,bomId);
        if(!OrderStatusEnums.BomStatus.CREATE.getStatusCode().equals(bomInfoTmp.getUseType())){
            return Result.error("已提交审核");
        }

        BomInfoAudit audit = bomInfoAuditService.getById(BomInfoAudit.class,bomId);
        if(audit!=null){
            return Result.error("已提交审核");
        }

        if(bomInfoTmpService.audit(bomId)){
            return Result.OK();
        }
        return Result.error("提交出错");
    }

}
